#include "sem.h"

#if 0 
 创建信号量集合
 nsems:信号量集合中信号量的数量
 values:信号量值的集合
#endif
int sem_create(int nsems, unsigned short *values){
	key_t key=ftok("../",01);	
	if(key==-1){
		perror("ftok:");
		return -1;
	}
	int semid=semget(key,nsems,IPC_CREAT|0666);
	if(semid==-1){
		perror("semget");
		return -1;
	}
	union semun sem;
	sem.array=values;
	int ret=semctl(semid,0,SETALL,sem);
	if(ret==-1){
		perror("semctl");
		return -1;
	}
	return semid;
}
// 占用资源
int sem_occupy(int semid,int semnum){
	struct sembuf sops;
	sops.sem_num=semnum;
	sops.sem_op=-1;
	sops.sem_flg=SEM_UNDO;
	int ret = semop(semid,&sops,1);
	if(ret==-1){
		perror("semop");
	}
	return ret;
}
// 释放资源
int sem_release(int semid,int semnum){
	struct sembuf sops;
	sops.sem_num=semnum;
	sops.sem_op=1;
	sops.sem_flg=SEM_UNDO;
	int ret = semop(semid,&sops,1);
	if(ret==-1){
		perror("semop");
	}
	return ret;

}
// 删除信号量集合
int del_semaphore_set(int semid){
	int ret=semctl(semid,0,IPC_RMID,NULL);
	if(ret==-1){
		perror("semctl");
	}
	return ret;
}
